import React, { useState, useEffect } from 'react';
import {
    Table,
    Button,
    Form,
    Input,
    InputNumber,
    Modal,
    message,
    Popconfirm,
    Select,
    Upload, // Add Upload for bulk import
    Space, // Add Space for button grouping
    Tag // Add Tag for potential future use or consistency
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, UploadOutlined } from '@ant-design/icons'; // Add SearchOutlined and UploadOutlined
import { adminAPI } from '../services/api';
import * as XLSX from 'xlsx'; // Import xlsx for Excel parsing

const { Option } = Select;

const MenuItemManagement = () => {
    const [menuItems, setMenuItems] = useState([]);
    const [loading, setLoading] = useState(false);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [editingItem, setEditingItem] = useState(null); // null for add, object for edit
    const [form] = Form.useForm();

    // State for Search functionality
    const [searchQuery, setSearchQuery] = useState('');

    // States for Bulk Import functionality
    const [importModalVisible, setImportModalVisible] = useState(false);
    const [fileList, setFileList] = useState([]);
    const [previewData, setPreviewData] = useState([]);
    const [importLoading, setImportLoading] = useState(false);

    useEffect(() => {
        fetchMenuItems();
    }, []);

    const fetchMenuItems = async () => {
        setLoading(true);
        try {
            const { data } = await adminAPI.getAllMenuItems();
            // Sort menu items by item_name for consistent display
            const sortedMenuItems = data.sort((a, b) => {
                return a.item_name.localeCompare(b.item_name);
            });
            setMenuItems(sortedMenuItems);
        } catch (error) {
            console.error('获取菜单项失败:', error);
            message.error('获取菜单项失败: ' + (error.response?.data?.message || error.message));
        } finally {
            setLoading(false);
        }
    };

    const handleAdd = () => {
        setEditingItem(null);
        form.resetFields();
        setIsModalVisible(true);
    };

    const handleEdit = (item) => {
        setEditingItem(item);
        form.setFieldsValue(item);
        setIsModalVisible(true);
    };

    const handleDelete = async (itemId) => {
        try {
            await adminAPI.deleteMenuItem(itemId);
            message.success('菜单项删除成功');
            fetchMenuItems();
        } catch (error) {
            console.error('删除菜单项失败:', error);
            message.error(error.response?.data?.message || '删除菜单项失败');
        }
    };

    const onFinish = async (values) => {
        setLoading(true);
        try {
            if (editingItem) {
                await adminAPI.updateMenuItem(editingItem.item_id, values);
                message.success('菜单项更新成功');
            } else {
                await adminAPI.addMenuItem(values);
                message.success('菜单项添加成功');
            }
            setIsModalVisible(false);
            form.resetFields();
            fetchMenuItems();
        } catch (error) {
            console.error('保存菜单项失败:', error);
            message.error(error.response?.data?.message || '保存菜单项失败');
        } finally {
            setLoading(false);
        }
    };

    // --- Bulk Import Functions ---
    const handleExcelFileUpload = (file) => {
        setImportLoading(true);
        const reader = new FileReader();

        reader.onload = (e) => {
            try {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });

                const sheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[sheetName];

                const json = XLSX.utils.sheet_to_json(worksheet, { header: 1, raw: false });

                if (json.length === 0) {
                    message.error('文件内容为空或格式不正确！');
                    setPreviewData([]);
                    setFileList([]);
                    return;
                }

                const headers = json[0];
                let rows = json.slice(1);

                const requiredHeaders = ['商品名称', '价格', '分类']; // Category is optional, but include for header check
                const trimmedHeaders = headers.map(h => typeof h === 'string' ? h.trim() : h);

                // Check if the first two headers are correct and if the total number of headers is at least 2 (for item_name and price)
                const isHeaderValid = trimmedHeaders[0] === requiredHeaders[0] && trimmedHeaders[1] === requiredHeaders[1] && headers.length >= 2;

                if (!isHeaderValid) {
                    message.error('Excel 文件标题行不符合要求！请确保至少是 "商品名称, 价格"。');
                    setPreviewData([]);
                    setFileList([]);
                    return;
                }

                rows = rows.filter(row => {
                    // Filter out rows where item_name is empty
                    return row[0] !== undefined && row[0] !== null && String(row[0]).trim() !== '';
                });

                if (rows.length === 0) {
                    message.error('文件中没有有效的商品数据可供导入！');
                    setPreviewData([]);
                    setFileList([]);
                    return;
                }

                const formattedPreview = rows.map((row, index) => {
                    return {
                        key: `preview-${index}`,
                        item_name: String(row[0] || '').trim(),
                        price: parseFloat(row[1]) || 0.00,
                        category: String(row[2] || '').trim() || null, // Category is optional
                    };
                });

                const invalidData = formattedPreview.filter(item => (
                    !item.item_name ||
                    isNaN(item.price) || item.price < 0
                ));

                if (invalidData.length > 0) {
                    message.warn(`部分导入数据格式不正确（共 ${invalidData.length} 条），请检查预览数据！`);
                }

                setPreviewData(formattedPreview);
                setFileList([file]);
                message.success(`${file.name} 文件读取成功，请预览并点击“开始导入”！`);
            } catch (error) {
                console.error('解析Excel文件失败:', error);
                message.error('文件解析失败，请检查文件格式。');
                setPreviewData([]);
                setFileList([]);
            } finally {
                setImportLoading(false);
            }
        };

        reader.onerror = () => {
            message.error('文件读取失败！');
            setImportLoading(false);
        };

        reader.readAsArrayBuffer(file);
        return false; // Prevent Ant Design from auto-uploading
    };

    const handleStartBulkImport = async () => {
        if (previewData.length === 0) {
            message.warn('没有数据可以导入！请先选择并解析Excel文件。');
            return;
        }

        setImportLoading(true);
        try {
            const importData = previewData.map(item => ({
                item_name: item.item_name,
                price: item.price,
                category: item.category,
            }));

            const response = await adminAPI.bulkImportMenuItems(importData);
            message.success(response.message || `成功导入 ${response.importedCount || 0} 个商品！`);
            setPreviewData([]);
            setFileList([]);
            setImportModalVisible(false);
            fetchMenuItems(); // Refresh menu items after import
        } catch (error) {
            console.error('批量导入失败:', error);
            message.error(error.response?.data?.message || error.response?.data?.error || '商品批量导入失败！');
        } finally {
            setImportLoading(false);
        }
    };
    // --- End Bulk Import Functions ---


    // Filter menu items based on search query
    const filteredMenuItems = menuItems.filter(item =>
        item.item_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        (item.category && item.category.toLowerCase().includes(searchQuery.toLowerCase()))
    );

    const columns = [
        { title: '商品名称', dataIndex: 'item_name', key: 'item_name' },
        { title: '价格 (¥)', dataIndex: 'price', key: 'price', render: price => `¥${parseFloat(price).toFixed(2)}` },
        { title: '分类', dataIndex: 'category', key: 'category' },
        {
            title: '操作',
            key: 'actions',
            render: (_, record) => (
                <Space size="middle"> {/* Use Space for consistent spacing */}
                    <Button
                        icon={<EditOutlined />}
                        onClick={() => handleEdit(record)}
                        size="small"
                        className="text-blue-500 hover:text-blue-700 transition-colors duration-200"
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确定删除此菜单项吗？"
                        onConfirm={() => handleDelete(record.item_id)}
                        okText="是"
                        cancelText="否"
                    >
                        <Button icon={<DeleteOutlined />} danger size="small" className="text-red-500 hover:text-red-700 transition-colors duration-200">
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    // Columns for previewing imported data
    const previewColumns = [
        { title: '商品名称', dataIndex: 'item_name', key: 'preview_item_name' },
        { title: '价格', dataIndex: 'price', key: 'preview_price', render: price => `¥${parseFloat(price).toFixed(2)}` },
        { title: '分类', dataIndex: 'category', key: 'preview_category' },
    ];

    return (
        <div className="min-h-screen bg-gray-100 p-6 font-inter antialiased">
            <div className="max-w-7xl mx-auto bg-white rounded-xl shadow-lg p-8">
                {/* Page Title */}
                <h1 className="text-4xl font-extrabold text-gray-800 mb-8 text-center">商品管理</h1>

                {/* Top Section: Add Button, Bulk Import Button & Search Input */}
                <div className="flex flex-col md:flex-row justify-between items-center mb-8 space-y-4 md:space-y-0">
                    <div className="flex space-x-4"> {/* Group Add and Bulk Import buttons */}
                        <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={handleAdd}
                            className="bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-6 rounded-lg shadow-md hover:shadow-lg transition-all duration-300 transform hover:scale-105"
                        >
                            添加商品
                        </Button>
                        <Button
                            type="default" // Changed to default for visual distinction
                            icon={<UploadOutlined />}
                            onClick={() => {
                                setImportModalVisible(true);
                                setFileList([]);
                                setPreviewData([]);
                            }}
                            className="bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-2 px-6 rounded-lg shadow-md hover:shadow-lg transition-all duration-300 transform hover:scale-105"
                        >
                            批量导入商品
                        </Button>
                    </div>
                    <Input
                        placeholder="搜索商品名称或分类"
                        prefix={<SearchOutlined className="text-gray-400" />}
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="w-full md:w-80 p-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500 shadow-sm"
                        allowClear
                    />
                </div>

                {/* Menu Item List Table */}
                <h2 className="text-2xl font-bold text-gray-700 mb-5 border-b pb-3 border-gray-200">所有商品列表</h2>
                <Table
                    dataSource={filteredMenuItems} // Use filtered data
                    columns={columns}
                    rowKey="item_id"
                    loading={loading}
                    bordered
                    pagination={{ pageSize: 10, showSizeChanger: true, showQuickJumper: true }}
                    locale={{ emptyText: '暂无商品数据，请添加' }}
                    className="rounded-lg shadow-md overflow-hidden"
                />

                {/* Add/Edit Modal */}
                <Modal
                    title={<span className="text-xl font-semibold text-gray-800">{editingItem ? '编辑商品' : '添加商品'}</span>}
                    open={isModalVisible}
                    onCancel={() => {
                        setIsModalVisible(false);
                        form.resetFields();
                        setEditingItem(null);
                    }}
                    footer={null} // Custom footer for buttons
                    destroyOnClose={true}
                    className="rounded-lg"
                >
                    <Form
                        form={form}
                        layout="vertical"
                        onFinish={onFinish}
                        initialValues={editingItem}
                    >
                        <Form.Item
                            name="item_name"
                            label={<span className="font-medium text-gray-700">商品名称</span>}
                            rules={[{ required: true, message: '请输入商品名称' }]}
                        >
                            <Input className="rounded-md border-gray-300 focus:border-blue-500 focus:ring-blue-500" />
                        </Form.Item>
                        <Form.Item
                            name="price"
                            label={<span className="font-medium text-gray-700">价格</span>}
                            rules={[{ required: true, message: '请输入价格' }, { type: 'number', min: 0, message: '价格不能为负数' }]}
                        >
                            <InputNumber min={0} step={0.01} style={{ width: '100%' }} className="rounded-md border-gray-300 focus:border-blue-500 focus:ring-blue-500" />
                        </Form.Item>
                        <Form.Item
                            name="category"
                            label={<span className="font-medium text-gray-700">分类</span>}
                        >
                            <Input placeholder="可选：如 食品、饮料、服务" className="rounded-md border-gray-300 focus:border-blue-500 focus:ring-blue-500" />
                        </Form.Item>
                        <Form.Item className="mt-6"> {/* Add margin top for spacing */}
                            <Space> {/* Use Space for button grouping */}
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    loading={loading}
                                    className="bg-green-600 hover:bg-green-700 text-white font-semibold py-2 px-6 rounded-lg shadow-md hover:shadow-lg transition-all duration-300 transform hover:scale-105"
                                >
                                    {editingItem ? '更新' : '添加'}
                                </Button>
                                <Button
                                    onClick={() => {
                                        setIsModalVisible(false);
                                        form.resetFields();
                                        setEditingItem(null);
                                    }}
                                    className="bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-2 px-6 rounded-lg shadow-md hover:shadow-lg transition-all duration-300 transform hover:scale-105"
                                >
                                    取消
                                </Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </Modal>

                {/* Bulk Import Modal */}
                <Modal
                    title={<span className="text-xl font-semibold text-gray-800">批量导入商品</span>}
                    open={importModalVisible}
                    onOk={handleStartBulkImport}
                    onCancel={() => {
                        setImportModalVisible(false);
                        setFileList([]);
                        setPreviewData([]);
                    }}
                    okText="开始导入"
                    cancelText="取消"
                    confirmLoading={importLoading}
                    destroyOnClose={true}
                    width={800}
                    className="rounded-lg"
                >
                    <p className="mb-4 text-gray-700">请上传Excel文件（支持.xlsx, .xls格式）。</p>
                    <Upload
                        accept=".xlsx, .xls"
                        beforeUpload={handleExcelFileUpload}
                        fileList={fileList}
                        onRemove={() => { setFileList([]); setPreviewData([]); }}
                        maxCount={1}
                    >
                        <Button icon={<UploadOutlined />} className="bg-gray-200 hover:bg-gray-300 text-gray-800 rounded-md shadow-sm">选择Excel文件</Button>
                    </Upload>
                    <div className="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg text-gray-700 text-sm">
                        <p className="font-semibold mb-2">文件格式要求：</p>
                        <ul className="list-disc list-inside ml-4 space-y-1">
                            <li>文件格式: Excel (xlsx 或 xls)</li>
                            <li>第一个为标题行: "商品名称", "价格", "分类"</li>
                            <li>分类字段为可选。</li>
                            <li>示例数据:</li>
                            <Table
                                dataSource={[
                                    { key: 'ex1', item_name: '矿泉水', price: 3.00, category: '饮料' },
                                    { key: 'ex2', item_name: '方便面', price: 8.50, category: '食品' },
                                    { key: 'ex3', item_name: '洗衣服务', price: 20.00, category: '服务' },
                                ]}
                                columns={previewColumns}
                                pagination={false}
                                size="small"
                                className="w-full mb-2 border border-blue-300 rounded-md"
                                bordered
                            />
                        </ul>
                    </div>

                    {previewData.length > 0 && (
                        <h2 className="mt-8 text-lg font-semibold text-gray-700">预览数据 (共 {previewData.length} 条)</h2>
                    )}
                    <Table
                        columns={previewColumns}
                        dataSource={previewData}
                        pagination={{ pageSize: 5 }}
                        bordered
                        size="small"
                        className="mt-4 rounded-lg shadow-sm"
                    />
                </Modal>
            </div>
        </div>
    );
};

export default MenuItemManagement;
